var express = require('express');
var router = express.Router();
let Query=require('../tools/db')
let {api_url}=require('../config/config')

/* 获取地区数据 */
router.get('/area',async (req, res, next)=>{
  let sql=`SELECT id,area_name FROM e_area`
  let [,result]=await Query(sql)
  res.send({
    code:200,
    msg: 'ok',
    result
  })
})

//获取年级数据
router.get('/grade',async (req, res, next)=>{
  let sql=`SELECT id,grade_name FROM e_grade`
  let [,result]=await Query(sql)
  res.send({
    code:200,
    msg: 'ok',
    result
  })
})

//获取学科数据
router.get('/subject',async (req, res, next)=>{
  let sql=`SELECT id,subject_name FROM e_subject`
  let [,result]=await Query(sql)
  res.send({
    code:200,
    msg: 'ok',
    result
  })
})

//获取考试类别
router.get('/leibie',async (req, res, next)=>{
  let sql=`SELECT id,category_name FROM e_category`
  let [,result]=await Query(sql)
  res.send({
    code:200,
    msg: 'ok',
    result
  })
})

//获取课程列表数据
router.get('/list',async (req, res, next)=>{
  let {area='',grade='',subject='',category='',page=1,pageSize=6}=req.query
  page=Number(page)
  pageSize=Number(pageSize)
  let whereStr=''
  //地区
  if(area!=''){
    if(whereStr==''){
      whereStr=`WHERE area_name="${area}"`
    }else{
      whereStr+=` AND area_name="${area}"`
    }
  }

  //年级
  if(grade!=''){
    if(whereStr==''){
      whereStr=`WHERE grade_name="${grade}"`
    }else{
      whereStr+=` AND grade_name="${grade}"`
    }
  }

  //科目
  if(subject!=''){
    if(whereStr==''){
      whereStr=`WHERE subject_name="${subject}"`
    }else{
      whereStr+=` AND subject_name="${subject}"`
    }
  }

  //地区
  if(category!=''){
    if(whereStr==''){
      whereStr=`WHERE category_name="${category}"`
    }else{
      whereStr+=` AND category_name="${category}"`
    }
  }


  let sql1=`SELECT * FROM e_course ${whereStr}`
  let [,res1]=await Query(sql1)
  let totalNum=res1.length
  let totalPage=Math.ceil(totalNum/pageSize)
  let sql2=`SELECT id,cid,title,price,CONCAT('${api_url}','/upload/course/',image_src) AS image_src,type_name,area_name,subject_name FROM e_course ${whereStr} ORDER BY id DESC LIMIT ${(page-1)*pageSize},${pageSize}`
  let [,res2]=await Query(sql2)
  res.send({
    code:200,
    msg: 'ok',
    result:{
      page,
      pageSize,
      totalNum,
      totalPage,
      date: res2
     }
  })

})

module.exports = router;